package com.bxd.baodan.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Message;
import android.os.PowerManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.VideoCommentItem;
import com.bxd.baodan.item.VideoDetailItem;
import com.bxd.baodan.util.DialogUtil;
import com.bxd.baodan.util.ImageUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.NetUtil.RequestStringListener;
import com.bxd.baodan.util.ShareUtil;
import com.bxd.baodan.util.ViewUtil;
import com.bxd.baodan.widget.MediaController;
import com.bxd.baodan.widget.ShareContentDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

public class VideoDetailActivity extends BaseListActivity<VideoCommentItem> {

    private int mWidth;
    private TextView mTvTitle;
    private TextView tv_good_num;
    private TextView tv_played_num;
    private ImageView iv_good;
    private VideoDetailItem detailItem = new VideoDetailItem(); //
    private TextView tv_content;
    private com.bxd.baodan.widget.VideoView mVideoView;
    private EditText et_comment;
    private TextView tv_send;
    private ImageView iv_share;
    private Handler handler;
    private FrameLayout frame;
    private TextView tv_title;
    private ProgressBar pb;
    private ImageView playImageView;
    private LinearLayout rl_1;
    private String a_id;

    TextView tv_collect;
    ImageView iv_collect;

    /**
     * 播放状态handler
     */
    private Handler controllerHandler;
    private static final int STOPPLAYBACK = 1004;// 完全停止播放
    private static final int STOPPLAY = 1001;// 停止播放
    private static final int SEEKTO = 1002;// 快进到
    private static final int START = 1003;// 开始播放

    private long lastScreenState; // 状态记录
    private int screenWidth;
    private int screenHeight;
    private ImageView back;
    HandlerThread handlerThread = new HandlerThread("MediaControllerHandler");
    private MediaController mc;
    int video_zan_num;


    @Override
    protected int getActivityLayout() {
        return R.layout.activity_video_detail;
    }

    @Override
    protected void preDone() {
        creatHandler();

        WindowManager wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();

        Intent intent = this.getIntent();

        a_id = intent.getExtras().getString("video_id");

        if (mTvTitle != null) {
            mTvTitle.setHeight(mWidth / 10);
            mTvTitle.setTextSize(mWidth / 24);
        }
        //    getActionBar().hide(); // 隐藏actionbar
        findViewById(R.id.bar_content).setVisibility(View.GONE);
        initView();
        initData();
        setNetUtil();
        autoRefresh();
        handlerThread.start();
        initControllerHanlder();

    }

    @Override
    protected void preBundle(Bundle savedInstanceState) {
        super.preBundle(savedInstanceState);
        if (savedInstanceState != null) {
            lastScreenState = savedInstanceState.getLong("lastPosition");
        }
    }

    @Override
    protected Type getTypeToken() {
        return new TypeToken<List<VideoCommentItem>>() {
        }.getType();
    }

    @Override
    protected int getItemLayout() {
        return R.layout.video_comment_item;
    }

    @Override
    protected void setNetUtil() {
        //     netUtil = new NetUtil(this, JsonApi.VIDEO_COMMENT);
        netUtil = new NetUtil("comment/videocomment", VideoDetailActivity.this);

        try {
            netUtil.setParams("a_id ", a_id);  //145940
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void convert(final ViewHolder holder, final VideoCommentItem item) {
        ImageUtil.setAvatarToRounderCorner(VideoDetailActivity.this, item.ue_avatar,
                ((ImageView) holder.getView(R.id.answer_avatar)), true);
        holder.setText(R.id.commenter, item.ue_realname);
        holder.setText(R.id.tv_comment_content, item.co_content);
        holder.setText(R.id.tv_time, item.co_addtime);
        holder.setText(R.id.comment_praise_count, item.co_liker + "");
        if (item.isLike.equals("0")) {
            holder.setImageResource(R.id.iv_comment_praise, R.drawable.zan_gray_s);
        }
        if (item.isLike.equals("1")) {
            holder.setImageResource(R.id.iv_comment_praise, R.drawable.zan_green_s);
        }


        holder.getView(R.id.iv_comment_praise).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginInfo.getInstance(App.getContext()).isLogin()) {
                    NetUtil commentNet = new NetUtil("comment/commentlike", VideoDetailActivity.this);
                    commentNet.setParams("a_id", a_id);
                    commentNet.setParams("co_id", item.co_id);
                    commentNet.postRequest("", new RequestStringListener() {
                        @Override
                        public void onComplete(String result) {
                            if (JSONUtil.isSuccess(result)) {

                                String co_praise_count = ((TextView) holder.getView(R.id.comment_praise_count)).getText().toString();
                                int num = Integer.parseInt(co_praise_count);

                                String action = JSONUtil.getData("action", JSONUtil.getData(result));

                                if (action.equals("1")) {
                                    item.isLike = "1";
                                    item.co_liker = (num + 1) + "";
                                    holder.setImageResource(R.id.iv_comment_praise, R.drawable.zan_green_s);
                                    holder.setText(R.id.comment_praise_count, (num + 1) + "");

                                } else if (action.equals("-1")) {
                                    item.isLike = "0";
                                    item.co_liker = (num - 1) + "";
                                    holder.setImageResource(R.id.iv_comment_praise, R.drawable.zan_gray_s);
                                    holder.setText(R.id.comment_praise_count, (num - 1) + "");
                                }
                            }
                        }
                    });
                } else {
                    showToast("登录后才能点赞");
                }


            }
        });
    }


    /**
     * 初始化view对象
     */
    private void initView() {


        rl_1 = (LinearLayout) findViewById(R.id.rl_1);
        pb = (ProgressBar) findViewById(R.id.probar);
        mVideoView = (com.bxd.baodan.widget.VideoView) findViewById(R.id.videoview);
        et_comment = (EditText) findViewById(R.id.et_comment);
        tv_send = (TextView) findViewById(R.id.tv_send);
        frame = (FrameLayout) findViewById(R.id.frame);
        back = (ImageView) findViewById(R.id.back);
        playImageView = (ImageView) findViewById(R.id.iv_play);

        //添加headerView
        View header = View.inflate(this, R.layout.video_header, null);
        listView.addHeaderView(header);

        tv_good_num = (TextView) header.findViewById(R.id.tv_good_num);
        tv_played_num = (TextView) header.findViewById(R.id.tv_played_num);
        iv_good = (ImageView) header.findViewById(R.id.iv_good);
        tv_content = (TextView) header.findViewById(R.id.tv_content);
        tv_title = (TextView) header.findViewById(R.id.tv_title);
        iv_share = (ImageView) header.findViewById(R.id.iv_share);

        iv_collect = (ImageView) header.findViewById(R.id.iv_collect);
        tv_collect = (TextView) header.findViewById(R.id.tv_collect);

        iv_collect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginInfo.getInstance(VideoDetailActivity.this).isLogin()) {
                    NetUtil clNet = new NetUtil(VideoDetailActivity.this, JsonApi.COLLECT_MICROREADING);
                    clNet.setParams("aid", a_id);
                    clNet.postRequest("", new RequestStringListener() {
                        @Override
                        public void onComplete(String result) {
                            if (JSONUtil.isSuccess(result)) {

                                try {
                                    JSONObject json = new JSONObject(JSONUtil.getData(result));
                                    boolean b = json.getBoolean("isCollected");
                                    iv_collect.setImageResource(b ? R.drawable.sc_green : R.drawable.sc_gray);
                                    tv_collect.setText(b ? "已收藏" : "收藏");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        }
                    });
                } else {
                    showToast("请先登录");
                }

            }
        });


        tv_send.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        iv_good.setOnClickListener(this);
        back.setOnClickListener(this);
        tv_title.setOnClickListener(this);
        playImageView.setOnClickListener(this);
        mVideoView.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                // 重置状态
                playImageView.setVisibility(View.VISIBLE);
                pb.setVisibility(View.INVISIBLE);
                showToast("无法播放该视频");
                return true;
            }
        });
        mVideoView.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.seekTo(1);
                mVideoView.setBackgroundColor(Color.parseColor("#666666"));
                mVideoView.setVisibility(View.INVISIBLE); // 不可视黑色背景
                playImageView.setVisibility(View.VISIBLE);
            }
        });

        mVideoView.setOnInfoListener(new OnInfoListener() {

            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {

                if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                    pb.setVisibility(View.VISIBLE);
                } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                    pb.setVisibility(View.INVISIBLE);
                }
                return false;
            }
        });

    }


    private void initData() {

        // 请求
        NetUtil netUtil = new NetUtil(this, JsonApi.VIDEO_DETAIL);
        netUtil.setParams("a_id", a_id);
        netUtil.postRequest("加载中", new RequestStringListener() {

            @Override
            public void onComplete(String result) {

                try {

                    JSONObject object = new JSONObject(result);

                    if (object.getInt("code") == 0) {

                        String data = object.optString("data");
                        detailItem = new Gson().fromJson(data,
                                new TypeToken<VideoDetailItem>() {
                                }.getType());

                        tv_title.setText(detailItem.a_title);

                        video_zan_num = Integer.parseInt(detailItem.a_laud);

                        tv_good_num.setText("点赞" + "(" + video_zan_num + ")");
                        tv_played_num.setText(detailItem.a_view_count + "次");


                        tv_content.setMaxLines(2);
                        tv_content.setEllipsize(TextUtils.TruncateAt.END);
                        Spanned fromHtml = Html.fromHtml(detailItem.a_content);
                        tv_content.setText(fromHtml);


                        if (detailItem.a_islaud == 1) {
                            iv_good.setImageResource(R.drawable.zan_green);

                        } else {
                            iv_good.setImageResource(R.drawable.zan_gray);

                        }

                        if (LoginInfo.getInstance(VideoDetailActivity.this).isLogin() &&
                                detailItem.isCollect.equals("1")) {
                            iv_collect.setImageResource(R.drawable.sc_green);
                            tv_collect.setText("已收藏");

                        } else {
                            iv_collect.setImageResource(R.drawable.sc_gray);
                            tv_collect.setText("收藏");
                        }
                        startToPlayVideo();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    @Override
    protected String getArrayStr(String json_data) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_play:
                startToPlayVideo();
                break;

            case R.id.iv_good: // 点赞

                if (!LoginInfo.getInstance(VideoDetailActivity.this).isLogin()) {
                    DialogUtil.getInstance().showToast(VideoDetailActivity.this,
                            "登录后才能点赞");
                    return;
                }
                NetUtil util = new NetUtil(VideoDetailActivity.this,
                        JsonApi.VIDEO_LAUD);
                util.setParams("a_id ", detailItem.a_id);
                util.postRequest("", new RequestStringListener() {

                    @Override
                    public void onComplete(String result) {
                        // 点赞结果
                        JSONObject obj;
                        try {
                            obj = new JSONObject(result);
                            int code = obj.optInt("code");
                            String msg = obj.optString("msg");
                            if (code == 0) {
                                showToast(msg);
                                if (msg.equals("点赞成功")) {
                                    iv_good.setImageResource(R.drawable.zan_green);
                                    tv_good_num.setText("点赞" + "(" + (++video_zan_num) + ")");

                                } else if (msg.equals("取消点赞")) {
                                    iv_good.setImageResource(R.drawable.zan_gray);
                                    tv_good_num.setText("点赞" + "(" + (video_zan_num == 0 ? 0 : --video_zan_num) + ")");
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

                break;

            case R.id.tv_send:
                // 判断是否登录
                String et_content = et_comment.getText().toString().trim();
                if (TextUtils.isEmpty(et_content)) {
                    showToast("请输入有效的评论内容");
                    return;
                } else {
                    if (!LoginInfo.getInstance(VideoDetailActivity.this).isLogin()) {
                        DialogUtil.getInstance().showToast(
                                VideoDetailActivity.this, "登录后才能进行评论");
                        return;

                    } else {

                        NetUtil util2 = new NetUtil(VideoDetailActivity.this,
                                JsonApi.VIDEO_ADD_COMMENT);
                        util2.setParams("a_id", a_id);
                        util2.setParams("content", et_content);

                        util2.postRequest("提交中", new RequestStringListener() {

                            @Override
                            public void onComplete(String result) {
                                // Log.i("评论返回结果", result);
                                try {
                                    JSONObject obj = new JSONObject(result);
                                    int code = obj.optInt("code");
                                    String msg = obj.optString("msg");
                                    if (code == 0) { // success
                                        // 重新请求数据
                                        autoRefresh();
                                        et_comment.setText("");
                                    } else {
                                        showToast(msg);
                                    }

                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                        });

                    }

                }
                break;

            case R.id.iv_share:
                shareMessage(detailItem.a_title, detailItem.a_image, detailItem.share_url, detailItem.share_url);
                break;
            case R.id.back:
                if (fullscreen) { // 不是竖屏先切回竖屏
                    doFullScreen();
                } else {
                    finish();
                }
                break;

            case R.id.tv_title:
                Spanned fromHtml = Html.fromHtml(detailItem.a_content);
                tv_content.setText(fromHtml);
                int line = tv_content.getLineCount();

                if (line > 2) {
                    //isExpand
                    tv_content.setEllipsize(TextUtils.TruncateAt.END);
                    tv_content.setMaxLines(2);
                } else {
                    tv_content.setEllipsize(null);
                    tv_content.setMaxLines(Integer.MAX_VALUE);
                }
                Drawable drawable;
                //  drawable = getResources().getDrawable(tv_content.isExpanded() ? R.drawable.ss_down : R.drawable.ss_up);
                drawable = getResources().getDrawable(line > 2 ? R.drawable.ss_up : R.drawable.ss_down);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                tv_title.setCompoundDrawables(null, null, drawable, null);
                //   tv_content.setExpanded(!tv_content.isExpanded());
                break;
            default:
                break;
        }

    }

    /**
     * context 上下文
     * title   分享的标题
     * content 分享的內容
     * url     分享的url
     *
     * @param imgUrl 分享时候用到的图标
     */

    private void shareMessage(String content, String imgUrl, String shortLink,
                              String id) {
        Log.i("测试", content + imgUrl + shortLink + id);

        // imgUrl = imgUrl
        ShareContentDialog scd = new ShareContentDialog(this, "来自保险岛的分享",
                content, shortLink, imgUrl, id, handler);
        scd.show();
    }


    private void creatHandler() {
        if (handler == null) {
            handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    String platFromName = msg.getData().getString(
                            "platFormName");
                    String id = msg.getData().getString("params");
                    switch (msg.what) {
                        case ShareUtil.SHARE_ERROR:
                            Toast.makeText(VideoDetailActivity.this, "分享失败",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case ShareUtil.SHARE_COMPLETED:
                            Toast.makeText(VideoDetailActivity.this, "分享成功",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case ShareUtil.SHARE_CANCELED:
                            showToast("取消分享");
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }
    }


    private void initControllerHanlder() {

        controllerHandler = new Handler(handlerThread.getLooper(),
                new Callback() {

                    @Override
                    public boolean handleMessage(Message msg) {
                        switch (msg.what) {
                            case STOPPLAYBACK:
                                break;
                            case STOPPLAY:
                                if (mVideoView != null && mVideoView.isPlaying())
                                    mVideoView.pause();
                                break;
                            case SEEKTO:
                                if (mVideoView != null) {
                                    mVideoView.seekTo((int) lastScreenState);
                                    lastScreenState = 0;
                                }
                                break;
                            case START:
                                if (mVideoView != null) {
                                    mVideoView.start();
                                }
                                break;
                            default:
                                break;
                        }
                        return true;
                    }
                });

    }

    /**
     * 播放视频
     */
    private void startToPlayVideo() {
        if (detailItem == null) {
            // 无法播放
            return;
        } else {
            if (("").equals(detailItem.a_filesrc) || detailItem.a_filesrc == null) {
                // 视频地址不正确
            } else {
                pb.setVisibility(View.VISIBLE);
                mVideoView.setVisibility(View.VISIBLE);
                // pb.setVisibility(View.VISIBLE);
                playImageView.setVisibility(View.INVISIBLE);
                Log.i("detailItem.a_filesrc", detailItem.a_filesrc);
                // https://www.bxd365.com/ali/ajaxm3u8/af_id/360/action/.m3u8
                String url = detailItem.a_filesrc.replace("https", "http");

                mVideoView.setVideoPath(url);
                mc = new MediaController(this, true, frame);
                mc.setOnFullScreenImageClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        doFullScreen();

                    }
                });
                mVideoView.setMediaController(mc);
                if (isScreenOn(this)) {
                    if (lastScreenState > 0) {
                        mVideoView.seekTo((int) lastScreenState);
                        lastScreenState = 0;
                    }
                }

                mVideoView.start();
                mVideoView.setOnPreparedListener(new OnPreparedListener() {

                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        pb.setVisibility(View.INVISIBLE); // 在这里不可视
                        mVideoView.setBackgroundColor(0);
                        // mp.start();
                        // 发送广播
                    }
                });

                mVideoView.setOnErrorListener(new OnErrorListener() {

                    @Override
                    public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                        // TODO Auto-generated method stub

                        LogUtil.e(arg1 + "=====" + arg2);
                        return false;
                    }
                });
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存选择RadioButton的Id
        mPositionWhenPaused = mVideoView.getCurrentPosition();
        outState.putLong("lastPosition", mVideoView.getCurrentPosition());
    }

    private boolean fullscreen = false;

    // 设置横竖屏切换
    private void doFullScreen() {

        if (!fullscreen) {// 设置RelativeLayout的全屏模式
            // Log.i("屏幕的宽高", screenHeight + "====" + screenWidth);
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                    screenHeight, screenWidth);
            mVideoView.setLayoutParams(lp);

            // mVideoView.setLayoutParams(layoutParams);
            fullscreen = true;// 改变全屏/窗口的标记
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            rl_1.setVisibility(View.GONE);
        } else {// 设置RelativeLayout的窗口模式

            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                    screenWidth, ViewUtil.dip2px(this, 200));
            mVideoView.setLayoutParams(lp);
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 设置横竖屏
            }
            fullscreen = false;// 改变全屏/窗口的标记
            rl_1.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 判断是否处于锁屏的状态
     *
     * @param context
     * @return
     */
    public boolean isScreenOn(Context context) {
        PowerManager pm = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        if (pm.isScreenOn()) {
            return true;
        }
        return false;
    }

    // 暂停
    private long mPositionWhenPaused = -1;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mVideoView) { // 对象清空
            mVideoView = null;
        }
    }

    @Override
    public void onPause() {
        // 当activity暂停时候停止播放视频
        super.onPause();
        try {
            mPositionWhenPaused = mVideoView.getCurrentPosition();
        } catch (Exception e) {
            e.printStackTrace();
        }
        lastScreenState = mPositionWhenPaused;
        controllerHandler.sendEmptyMessage(STOPPLAY);
    }

    @Override
    public void onResume() {
        super.onResume();
        // activity被唤醒的时候继续从上次停留的位置播放视频
        if (mPositionWhenPaused >= 0) {
            controllerHandler.sendEmptyMessage(SEEKTO);
            // playImageView.setVisibility(View.INVISIBLE); // TODO
        }
        if (mVideoView.getVisibility() == View.INVISIBLE) {
            // playImageView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (fullscreen) { // 判断是不是竖屏
                doFullScreen();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
